<template>
  <Header />
  <div class="filter-section" ref="filterSectionRef">
    <div class="filter-title">全部商品</div>

    <!-- 分类筛选 - 单选 -->
    <div class="filter-row">
      <div class="filter-label">分类</div>
      <ul class="filter-options">
        <li
          v-for="category in categories"
          :key="category.id"
          :class="{ active: selectedCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          {{ category.name }}
        </li>
      </ul>
    </div>

    <!-- 品牌筛选 - 多选 -->
    <div class="filter-row">
      <div class="filter-label">品牌</div>
      <div class="filter-content">
        <ul
          class="filter-options brand-options"
          :class="{ expanded: brandsExpanded }"
        >
          <li
            v-for="brand in brands"
            :key="brand.id"
            :class="{ active: selectedBrands.includes(brand.id) }"
            @click="toggleBrand(brand.id)"
          >
            {{ brand.name }}
          </li>
        </ul>
        <div class="brand-toggle" @click="toggleBrandsExpand">
          {{ brandsExpanded ? '收起' : '更多' }}
          <i :class="brandsExpanded ? '▲' : '﹀'"></i>
        </div>
      </div>
    </div>

    <!-- 高级筛选 - 带下拉菜单 -->
    <div class="filter-row">
      <div class="filter-label">高级筛选</div>
      <ul class="filter-options">
        <li
          v-for="option in advancedOptions"
          :key="option.id"
          class="advanced-option"
          :class="{ active: hasSelectedItems(option.id) }"
          @mouseenter="handleMouseEnter(option.id)"
          @mouseleave="handleMouseLeave"
          :ref="setAdvancedOptionRef"
        >
          {{ option.name }}
          <div
            v-if="activeDropdown === option.id"
            class="dropdown-menu"
            :style="dropdownStyles[option.id]"
            @mouseenter="handleDropdownEnter"
            @mouseleave="handleDropdownLeave"
          >
            <div
              v-for="item in option.items"
              :key="item"
              class="dropdown-menu-item"
              :class="{
                'dropdown-active': isAdvancedItemSelected(option.id, item),
              }"
              @click="toggleAdvancedItem(option.id, item)"
            >
              {{ item }}
            </div>
          </div>
        </li>
      </ul>
    </div>

    <!-- 已选筛选条件 -->
    <div class="selected-filters" v-if="selectedFilters.length > 0">
      <div class="filter-label">已选</div>
      <div class="selected-tags">
        <span
          v-for="filter in selectedFilters"
          :key="filter.id"
          class="selected-tag"
        >
          {{ filter.text }}
          <span class="remove" @click="removeFilter(filter)">×</span>
        </span>
      </div>
    </div>

    <!-- 排序栏 -->
    <div class="sort-bar">
      <button
        v-for="sort in sortOptions"
        :key="sort.id"
        :class="[{ active: selectedSort === sort.id }, sort.class]"
        @click="selectSort(sort.id)"
      >
        {{ sort.name }}
      </button>
    </div>
  </div>
  <Product />
  <Footer />
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'

// 分类数据 - 单选
const categories = ref([
  { id: 1, name: '手机' },
  { id: 2, name: '手机配件' },
  { id: 3, name: '模拟对讲机' },
  { id: 4, name: '合约机' },
  { id: 5, name: '数字对讲机' },
  { id: 6, name: '上网卡' },
  { id: 7, name: '手机租赁' },
  { id: 8, name: '公网对讲机' },
  { id: 9, name: '赠品' },
  { id: 10, name: '保障服务' },
])

// 品牌数据 - 多选
const brands = ref([
  { id: 1, name: 'Apple' },
  { id: 2, name: '小米 (MI)' },
  { id: 3, name: '华为 (HUAWEI)' },
  { id: 4, name: 'vivo' },
  { id: 5, name: '荣耀 (HONOR)' },
  { id: 6, name: 'OPPO' },
  { id: 7, name: 'CUKTECH' },
  { id: 8, name: '品胜 (PISEN)' },
  { id: 9, name: '一加' },
  { id: 10, name: '绿联 (UGREEN)' },
  { id: 11, name: '京东京造' },
  { id: 12, name: '尊匠' },
  { id: 13, name: '真我 (realme)' },
  { id: 14, name: 'ANKER' },
  { id: 15, name: 'ANKER' },
  { id: 16, name: 'ANKER' },
  { id: 17, name: 'ANKER' },
])

// 高级筛选数据 - 带下拉菜单
const advancedOptions = ref([
  {
    id: 1,
    name: '功能',
    items: [
      '散热',
      '可旋转',
      '抗指纹',
      '抗氧化',
      '防震',
      '护眼膜',
      '防指纹',
      '防摔',
    ],
  },
  {
    id: 2,
    name: '工艺',
    items: ['防偷窥', '防磨', '磁吸', '便携', '补光', '防尘', '防爆'],
  },
  {
    id: 3,
    name: '长度',
    items: ['10cm以下', '10-20cm', '20-30cm', '30-50cm', '50cm以上'],
  },
  {
    id: 4,
    name: '贴膜神器',
    items: ['自动贴合', '精准定位', '无尘仓', '辅助工具'],
  },
  {
    id: 5,
    name: 'CPU型号',
    items: ['骁龙8系列', '骁龙7系列', '天玑系列', '麒麟系列', 'A系列'],
  },
  {
    id: 6,
    name: '适用场景',
    items: ['游戏', '摄影', '商务', '学生', '户外'],
  },
  {
    id: 7,
    name: '机身内存',
    items: ['64GB', '128GB', '256GB', '512GB', '1TB'],
  },
  {
    id: 8,
    name: '运行内存',
    items: ['4GB', '6GB', '8GB', '12GB', '16GB'],
  },
  {
    id: 9,
    name: '屏幕材质',
    items: ['LCD', 'OLED', 'AMOLED', 'Mini-LED'],
  },
  {
    id: 10,
    name: '屏幕分辨率',
    items: ['720P', '1080P', '2K', '4K'],
  },
  {
    id: 11,
    name: '后摄主像素',
    items: ['1200万', '4800万', '6400万', '1亿', '2亿'],
  },
  {
    id: 12,
    name: '电池容量',
    items: ['3000mAh以下', '3000-4000mAh', '4000-5000mAh', '5000mAh以上'],
  },
])

// 排序选项
const sortOptions = ref([
  { id: 1, name: '综合', class: '' },
  { id: 2, name: '销量 ↓', class: '' },
  { id: 3, name: '价格 ↑', class: '' },
  { id: 4, name: '价格区间 ▾', class: '' },
  { id: 5, name: '京东物流', class: '' },
  { id: 6, name: '国家补贴', class: 'green' },
  { id: 7, name: '官方直降', class: 'red' },
  { id: 8, name: '货到付款', class: '' },
  { id: 9, name: '仅显示有货', class: 'red-outline' },
])

// 响应式数据
const selectedCategory = ref(1)
const selectedBrands = ref([2, 3])
const activeDropdown = ref<number | null>(null)
const selectedSort = ref(1)
const brandsExpanded = ref(false)
const selectedAdvancedItems = ref<Record<number, string[]>>({})
const dropdownStyles = ref<Record<number, any>>({})
const filterSectionRef = ref<HTMLElement>()
const advancedOptionElements = ref<Map<number, HTMLElement>>(new Map())
let dropdownTimer: number | null = null

// 计算属性
const selectedFilters = computed(() => {
  const filters: Array<{ id: string; text: string; type: string }> = []

  // 品牌筛选
  selectedBrands.value.forEach((brandId) => {
    const brand = brands.value.find((b) => b.id === brandId)
    if (brand) {
      filters.push({
        id: `brand-${brandId}`,
        text: brand.name,
        type: 'brand',
      })
    }
  })

  // 高级筛选
  Object.entries(selectedAdvancedItems.value).forEach(([optionId, items]) => {
    if (items.length > 0) {
      const option = advancedOptions.value.find(
        (o) => o.id === Number(optionId),
      )
      if (option) {
        items.forEach((item) => {
          filters.push({
            id: `advanced-${optionId}-${item}`,
            text: `${option.name}: ${item}`,
            type: 'advanced',
          })
        })
      }
    }
  })

  return filters
})

// 设置高级选项引用
const setAdvancedOptionRef = (el: any) => {
  if (el) {
    const option = advancedOptions.value.find((o) =>
      el.textContent?.includes(o.name),
    )
    if (option) {
      advancedOptionElements.value.set(option.id, el)
    }
  }
}

const selectCategory = (id: number) => {
  selectedCategory.value = id
}

const toggleBrand = (id: number) => {
  const index = selectedBrands.value.indexOf(id)
  if (index > -1) {
    selectedBrands.value.splice(index, 1)
  } else {
    selectedBrands.value.push(id)
  }
}

const selectSort = (id: number) => {
  selectedSort.value = id
}

const toggleBrandsExpand = () => {
  brandsExpanded.value = !brandsExpanded.value
}

const isAdvancedItemSelected = (optionId: number, item: string) => {
  return selectedAdvancedItems.value[optionId]?.includes(item) || false
}

const hasSelectedItems = (optionId: number) => {
  return selectedAdvancedItems.value[optionId]?.length > 0 || false
}

const toggleAdvancedItem = (optionId: number, item: string) => {
  if (!selectedAdvancedItems.value[optionId]) {
    selectedAdvancedItems.value[optionId] = []
  }

  const index = selectedAdvancedItems.value[optionId].indexOf(item)
  if (index > -1) {
    selectedAdvancedItems.value[optionId].splice(index, 1)
    if (selectedAdvancedItems.value[optionId].length === 0) {
      delete selectedAdvancedItems.value[optionId]
    }
  } else {
    selectedAdvancedItems.value[optionId].push(item)
  }
}

const removeFilter = (filter: { id: string; type: string }) => {
  if (filter.type === 'brand') {
    const brandId = Number(filter.id.split('-')[1])
    const index = selectedBrands.value.indexOf(brandId)
    if (index > -1) {
      selectedBrands.value.splice(index, 1)
    }
  } else if (filter.type === 'advanced') {
    const parts = filter.id.split('-')
    const optionId = Number(parts[1])
    const item = parts.slice(2).join('-')

    if (selectedAdvancedItems.value[optionId]) {
      const index = selectedAdvancedItems.value[optionId].indexOf(item)
      if (index > -1) {
        selectedAdvancedItems.value[optionId].splice(index, 1)
        if (selectedAdvancedItems.value[optionId].length === 0) {
          delete selectedAdvancedItems.value[optionId]
        }
      }
    }
  }
}

const handleMouseEnter = async (optionId: number) => {
  if (dropdownTimer) {
    clearTimeout(dropdownTimer)
    dropdownTimer = null
  }
  activeDropdown.value = optionId

  // 等待DOM更新后计算下拉菜单位置
  await nextTick()
  calculateDropdownPosition(optionId)
}

const handleMouseLeave = () => {
  dropdownTimer = setTimeout(() => {
    activeDropdown.value = null
  }, 150) // 延迟关闭，避免鼠标移动到下拉菜单时立即关闭
}

const handleDropdownEnter = () => {
  if (dropdownTimer) {
    clearTimeout(dropdownTimer)
    dropdownTimer = null
  }
}

const handleDropdownLeave = () => {
  activeDropdown.value = null
}

const calculateDropdownPosition = (optionId: number) => {
  const optionElement = advancedOptionElements.value.get(optionId)
  if (!optionElement || !filterSectionRef.value) return

  const dropdownElement = optionElement.querySelector(
    '.dropdown-menu',
  ) as HTMLElement
  if (!dropdownElement) return

  // 获取元素位置和尺寸
  const filterSectionRect = filterSectionRef.value.getBoundingClientRect()
  const optionRect = optionElement.getBoundingClientRect()

  // 计算相对于filter-section的位置
  const optionLeftRelative = optionRect.left - filterSectionRect.left

  // 计算下拉菜单的最大可用宽度
  const maxDropdownWidth = Math.min(536, filterSectionRect.width - 32) // 最大33.5rem(536px)或减去padding

  // 计算每行可以显示的选项数量
  const calculateItemsPerRow = () => {
    // 估算每个选项的平均宽度（包括间隙）
    const estimatedItemWidth = 100 // 根据实际样式估算
    const gap = 8 // gap大小
    const itemsPerRow = Math.floor(
      maxDropdownWidth / (estimatedItemWidth + gap),
    )
    return Math.max(1, Math.min(itemsPerRow, 6)) // 限制在1-6个之间
  }

  const itemsPerRow = calculateItemsPerRow()

  // 计算下拉菜单的理想宽度（基于每行选项数量）
  const idealDropdownWidth = Math.min(
    maxDropdownWidth,
    itemsPerRow * 100 + (itemsPerRow - 1) * 8, // 100px每个选项 + 间隙
  )

  // 计算左右两侧可用空间
  const spaceOnRight = filterSectionRect.width - optionLeftRelative
  const spaceOnLeft = optionLeftRelative + optionRect.width

  // 优先尝试右对齐（左对齐）
  let left = 0
  let right = 'auto'
  let width = `${idealDropdownWidth}px`

  // 如果右侧空间足够显示下拉菜单
  if (spaceOnRight >= idealDropdownWidth) {
    left = 0
    right = 'auto'
  }
  // 如果右侧空间不足，但左侧空间足够
  else if (spaceOnLeft >= idealDropdownWidth) {
    left = 'auto'
    right = 0
  }
  // 如果两侧空间都不够，则使用较小的空间
  else {
    // 选择空间更大的一侧
    if (spaceOnRight >= spaceOnLeft) {
      left = 0
      right = 'auto'
      width = `${Math.min(idealDropdownWidth, spaceOnRight)}px`
    } else {
      left = 'auto'
      right = 0
      width = `${Math.min(idealDropdownWidth, spaceOnLeft)}px`
    }
  }

  // 根据实际宽度重新计算每行选项数量
  const actualWidth = parseFloat(width)
  const recalculatedItemsPerRow = Math.max(
    1,
    Math.floor((actualWidth + 8) / (100 + 8)),
  )

  // 更新下拉菜单样式
  dropdownStyles.value[optionId] = {
    left: left,
    right: right,
    width: width,
    maxWidth: `${maxDropdownWidth}px`,
    '--items-per-row': recalculatedItemsPerRow,
  }
}
</script>

<style scoped lang="scss">
.filter-section {
  border: 0.0625rem solid #eee;
  border-radius: 0.375rem;
  padding: 1rem;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  gap: 0.625rem;
  max-width: 74.375rem;
  margin: 0.625rem auto;
  box-sizing: border-box;
  position: relative;

  .filter-title {
    font-weight: bold;
    font-size: 1rem;
    margin-bottom: 0.625rem;
  }

  .filter-row {
    display: flex;
    align-items: flex-start;
    gap: 0.5rem;
    min-height: 1.5rem;

    .filter-label {
      width: 4rem;
      color: #666;
      flex-shrink: 0;
      line-height: 1.5rem;
      font-size: 0.875rem;
      margin-top: 0.125rem;
    }

    .filter-content {
      display: flex;
      flex: 1;
      align-items: baseline;
      position: relative;
    }

    .filter-options {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 0.625rem;
      line-height: 1.5rem;
      flex: 1;
      list-style: none;
      margin: 0;
      padding: 0;

      li {
        cursor: pointer;
        padding: 0.125rem 1rem;
        border-radius: 0.1875rem;
        font-size: 0.75rem;
        white-space: nowrap;
        position: relative;

        &:hover {
          background-color: #f5f5f5;
        }

        &.active {
          color: #e4393c;

          &::before {
            content: '✔ ';
          }
        }
      }
    }

    // 品牌列表特殊样式
    .brand-options {
      max-height: 1.8rem;
      overflow: hidden;
      align-items: flex-start;

      &.expanded {
        max-height: none;
      }
    }

    .brand-toggle {
      cursor: pointer;
      padding: 0.125rem 0.5rem;
      border-radius: 0.1875rem;
      font-size: 0.75rem;
      white-space: nowrap;
      color: #666;
      background-color: #f5f5f5;
      display: flex;
      align-items: center;
      gap: 0.25rem;
      flex-shrink: 0;
      height: 1.5rem;
      margin-left: 0.625rem;

      &:hover {
        background-color: #e8e8e8;
        color: #e4393c;
      }

      i {
        font-size: 0.625rem;
      }
    }
  }

  // 已选筛选条件
  .selected-filters {
    display: flex;
    align-items: flex-start;
    gap: 0.5rem;
    margin-top: 0.5rem;

    .filter-label {
      width: 4rem;
      color: #666;
      flex-shrink: 0;
      line-height: 1.5rem;
      font-size: 0.875rem;
      margin-top: 0.125rem;
    }

    .selected-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;
      flex: 1;
    }

    .selected-tag {
      display: inline-flex;
      align-items: center;
      gap: 0.25rem;
      padding: 0.25rem 0.5rem;
      background-color: #fff2f2;
      color: #e4393c;
      border: 0.0625rem solid #f7c7c7;
      border-radius: 0.25rem;
      font-size: 0.75rem;
      line-height: 1;

      .remove {
        cursor: pointer;
        font-size: 1rem;
        line-height: 1;
        margin-left: 0.125rem;

        &:hover {
          color: #c00;
        }
      }
    }
  }

  // 高级筛选下拉菜单样式
  .advanced-option {
    position: relative;

    .dropdown-menu {
      position: absolute;
      top: calc(100% + 0.5rem);
      background: white;
      border-radius: 0.25rem;
      box-shadow: 0 0.125rem 0.5rem rgba(0, 0, 0, 0.1);
      z-index: 1000;
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;
      padding: 0.75rem;
      box-sizing: border-box;
      border: 0.0625rem solid #eee;
      max-width: 33.5rem;

      .dropdown-menu-item {
        padding: 0.275rem 0.75rem;
        font-size: 0.75rem;
        cursor: pointer;
        border-radius: 0.1875rem;
        white-space: nowrap;
        background-color: #f8f8f8;
        border: 0.0625rem solid transparent;
        flex: 1;
        min-width: calc(
          (100% - (var(--items-per-row, 1) - 1) * 0.5rem) /
            var(--items-per-row, 1)
        );
        max-width: calc(
          (100% - (var(--items-per-row, 1) - 1) * 0.5rem) /
            var(--items-per-row, 1)
        );
        box-sizing: border-box;
        text-align: center;
        color: #333;

        &:hover {
          background-color: #e8e8e8;
          border-color: #ddd;
        }

        &.dropdown-active {
          background-color: #e4393c;
          color: white;
          border-color: #e4393c;

          &::before {
            content: '✔ ';
          }
        }
      }
    }
  }

  .sort-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: 0.5rem;

    button {
      padding: 0.375rem 0.75rem;
      border: 0.0625rem solid #ddd;
      border-radius: 0.25rem;
      background-color: #fff;
      cursor: pointer;
      font-size: 0.75rem;
      flex-shrink: 0;

      &:hover {
        border-color: #e4393c;
        color: #e4393c;
      }

      &.active {
        background-color: #e4393c;
        color: #fff;
        border-color: #e4393c;
      }

      &.green {
        background-color: #e8f6ef;
        color: #37a873;
        border-color: #bce4cc;
      }

      &.red {
        background-color: #fff2f2;
        color: #e4393c;
        border-color: #f7c7c7;
      }

      &.red-outline {
        color: #e4393c;
        border-color: #e4393c;
        background-color: transparent;

        &:hover {
          background-color: #ffecec;
        }
      }
    }
  }
}

@media (max-width: 48rem) {
  .filter-section {
    padding: 0.75rem;

    .filter-row {
      flex-direction: column;
      align-items: flex-start;
      gap: 0.75rem;

      .filter-label {
        width: auto;
        margin-top: 0;
      }

      .filter-options {
        gap: 0.5rem;
      }
    }

    .advanced-option {
      .dropdown-menu {
        .dropdown-menu-item {
          min-width: calc(
            (100% - (var(--items-per-row, 1) - 1) * 0.5rem) /
              var(--items-per-row, 1)
          );
          max-width: calc(
            (100% - (var(--items-per-row, 1) - 1) * 0.5rem) /
              var(--items-per-row, 1)
          );
        }
      }
    }
  }
}

@media (max-width: 26.5625rem) {
  .filter-section {
    padding: 0.5rem;

    .filter-row {
      gap: 0.5rem;

      .filter-options {
        gap: 0.375rem;

        li {
          font-size: 0.7rem;
          padding: 0.125rem 0.375rem;
        }
      }
    }

    .sort-bar {
      gap: 0.375rem;

      button {
        padding: 0.25rem 0.5rem;
        font-size: 0.7rem;
      }
    }

    .advanced-option {
      .dropdown-menu {
        .dropdown-menu-item {
          min-width: calc(
            (100% - (var(--items-per-row, 1) - 1) * 0.375rem) /
              var(--items-per-row, 1)
          );
          max-width: calc(
            (100% - (var(--items-per-row, 1) - 1) * 0.375rem) /
              var(--items-per-row, 1)
          );
        }
      }
    }
  }
}

@media (max-width: 20rem) {
  .filter-section {
    .advanced-option {
      .dropdown-menu {
        padding: 0.5rem;

        .dropdown-menu-item {
          padding: 0.25rem 0.5rem;
          font-size: 0.65rem;
          min-width: calc(
            (100% - (var(--items-per-row, 1) - 1) * 0.25rem) /
              var(--items-per-row, 1)
          );
          max-width: calc(
            (100% - (var(--items-per-row, 1) - 1) * 0.25rem) /
              var(--items-per-row, 1)
          );
        }
      }
    }
  }
}
</style>
